package com.xiaol.websocketstomp.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * User: Ray.Shaw <p />
 * Time: 2018/8/1 09:47  <p />
 * Version: V1.0  <p />
 * Description:  <p />
 */

@Controller
public class SubController {

    @Autowired
    public SimpMessagingTemplate template;

    @RequestMapping(value = "/topic")
    public String index() {
        return "/topic";
    }

    @RequestMapping(value = "/topic1")
    public String index1() {
        return "/topic1";
    }

    @RequestMapping(value = "/queue")
    public String queue() {
        return "/queue";
    }

    @MessageMapping("/subscribe")
    public void subscribe(ReceiveMessage rm) {
        for(int i =1;i<=20;i++) {
            //广播使用convertAndSend方法，第一个参数为目的地，和js中订阅的目的地要一致
            template.convertAndSend("/topic/getResponse" + "/" + rm.getRaw(), rm.getContent());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    @MessageMapping("/queue")
    public void queuw(ReceiveMessage rm) {
        System.out.println("进入方法");
        for(int i =1;i<=20;i++) {
            /*广播使用convertAndSendToUser方法，第一个参数为用户id，此时js中的订阅地址为
            "/user/" + 用户Id + "/message",其中"/user"是固定的*/
            template.convertAndSendToUser("zhangsan","/message",rm.getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

//    @SendTo("/topic/greetings")
//    public Greeting greeting(HelloMessage message) throws Exception {
//        Thread.sleep(1000); // simulated delay
//        return new Greeting("YYY----Hello, " + message.getName() + "!");
//    }
}
